package com.yantu.controller.admin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.*;
import com.yantu.mapper.QuestionMapper;
import com.yantu.mapper.TextContentMapper;
import com.yantu.mapper.UserEventLogMapper;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.admin.AdminPageView;
import com.yantu.view.admin.addQuestion.QuestionView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-13
 */
@RestController
@RequestMapping("/admin")
@Api("管理端问题接口")
public class AdminQuestionController extends AdminUserEventLogController {
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    TextContentMapper textContentMapper;

    //题目列表
    //题目列表
    @GetMapping("/questionList")
    @ApiOperation("题目列表")
    public Result myListQuestion(){
        if(redisUtils.haskeysf("adminQuestionList")){
            System.out.println("缓存里面有");
            List<Object> objectList = (List<Object>) redisUtils.getValue("adminQuestionList");
            return Result.succ(200, "查询成功", objectList);
        }else {
            List<Question> questionList = questionMapper.selectList(null);
            List<Object> objects = new ArrayList<>();
            for (Question question : questionList) {
                if (question != null) {
                    Map map2 = new HashMap<>();
                    Question questionItem = questionMapper.selectById(question.getId());
                    map2.put("id", questionItem.getId());
                    map2.put("questionType", questionItem.getQuestionType());
                    map2.put("subjectId", questionItem.getSubjectId());
                    map2.put("score", questionItem.getScore());
                    map2.put("gradeLevel", questionItem.getGradeLevel());
                    map2.put("difficult", questionItem.getDifficult());
                    map2.put("correct", questionItem.getCorrect());
                    if (questionItem.getInfoTextContentId() != null) {
                        TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
                        JSONObject content1 = JSONObject.fromObject(textContent1.getContent());
                        map2.put("title", content1.getString("titleContent"));
                        map2.put("analyze", content1.getString("analyze"));
                        JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                        List<Object> answList = new ArrayList<>();
                        if (contentObject1.size() == 0) {
                            map2.put("questionItemObjects", null);
                        } else {
                            for (int j = 0; j < contentObject1.size(); j++) {
                                JSONObject xuanxiang = contentObject1.getJSONObject(j);
                                Map<String, String> map4 = new HashMap();
                                map4.put("prefix", xuanxiang.getString("prefix"));
                                map4.put("content", xuanxiang.getString("content"));
                                map4.put("score", xuanxiang.getString("score"));
                                answList.add(map4);
                            }
                            map2.put("questionItemObjects", answList);
                        }
                        objects.add(map2);
                    }
                }

            }
            redisUtils.saveValue("adminQuestionList",objects);
            return Result.succ(200, "查询成功", objects);
        }
    }
    //题目分页
    @GetMapping("/questions")
    @ApiOperation("题目分页信息")
    public Result myListQuestion(@ModelAttribute AdminPageView pageView){
        PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
        if(redisUtils.haskeysf("adminQuestionList"+pageView)){
            System.out.println("缓存里面有");
            Map map = (Map) redisUtils.getValue("adminQuestionList"+pageView);
            return Result.succ(200, "查询成功", map);
        }else {
            QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
            if (pageView.getId() != null) {
                queryWrapper.eq("id", pageView.getId());
            }
            if (pageView.getQuestionType() != null) {
                queryWrapper.eq("question_type", pageView.getQuestionType());
            }
            if (pageView.getLevel() != null) {
                queryWrapper.eq("question_type", pageView.getLevel());
            }
            if (pageView.getSubjectId() != null) {
                queryWrapper.eq("subject_id", pageView.getSubjectId());
            }
            List<Question> questionList = questionMapper.selectList(queryWrapper);
            List<Object> objects = new ArrayList<>();
            for (Question question : questionList) {
                if (question != null) {
                    Map map2 = new HashMap<>();
                    Question questionItem = questionMapper.selectById(question.getId());
                    map2.put("id", questionItem.getId());
                    map2.put("questionType", questionItem.getQuestionType());
                    map2.put("subjectId", questionItem.getSubjectId());
                    map2.put("score", questionItem.getScore());
                    map2.put("gradeLevel", questionItem.getGradeLevel());
                    map2.put("difficult", questionItem.getDifficult());
                    map2.put("correct", questionItem.getCorrect());
                    if (questionItem.getInfoTextContentId() != null) {
                        TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
//                    JSONArray contentArray1 = JSONArray.fromObject(textContent1.getContent());
////                    JSONObject content1=contentArray1.getJSONObject(0);
                        JSONObject content1 = JSONObject.fromObject(textContent1.getContent());

                        map2.put("title", content1.getString("titleContent"));
                        map2.put("analyze", content1.getString("analyze"));
                        JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                        List<Object> answList = new ArrayList<>();
                        if (contentObject1.size() == 0) {
                            map2.put("questionItemObjects", null);
                        } else {
                            for (int j = 0; j < contentObject1.size(); j++) {
                                JSONObject xuanxiang = contentObject1.getJSONObject(j);
                                Map<String, String> map4 = new HashMap();
                                map4.put("prefix", xuanxiang.getString("prefix"));
                                map4.put("content", xuanxiang.getString("content"));
                                map4.put("score", xuanxiang.getString("score"));
                                answList.add(map4);
                            }
                            map2.put("questionItemObjects", answList);
                        }

                        objects.add(map2);
                    }
                }

            }
            Map map = new HashMap<>();
            PageInfo pageInfo = new PageInfo(objects);
            int count = questionMapper.selectCount(queryWrapper);
            map.put("count", count);
            map.put("data", pageInfo);
            redisUtils.saveValue("adminQuestionList"+pageView,map);
            return Result.succ(200, "查询成功", map);
        }
    }

    //题目查询
    @GetMapping("/question/{id}")
    @ApiOperation("根据题目id查询题目")
    public Result getQuestionById(@PathVariable("id") Integer id) {
        if(redisUtils.haskeysf("adminQuestion"+id)){
            System.out.println("缓存里面有");
            Map map = (Map) redisUtils.getValue("adminQuestion"+id);
            return Result.succ(200, "查询成功", map);
        }else {
            System.out.println(id);
            Question question = questionMapper.selectById(id);
            System.out.println(question);
            if (question != null) {
                Map map2 = new HashMap<>();
                Question questionItem = questionMapper.selectById(id);
                map2.put("id", questionItem.getId());
                map2.put("questionType", questionItem.getQuestionType());
                map2.put("subjectId", questionItem.getSubjectId());
                map2.put("score", questionItem.getScore());
                map2.put("gradeLevel", questionItem.getGradeLevel());
                map2.put("difficult", questionItem.getDifficult());
                map2.put("correct", questionItem.getCorrect());
                if (questionItem.getInfoTextContentId() != null) {
                    TextContent textContent1 = textContentMapper.selectById(questionItem.getInfoTextContentId());
//                    JSONArray contentArray1 = JSONArray.fromObject(textContent1.getContent());
////                    JSONObject content1=contentArray1.getJSONObject(0);
                    JSONObject content1 = JSONObject.fromObject(textContent1.getContent());

                    map2.put("title", content1.getString("titleContent"));
                    map2.put("analyze", content1.getString("analyze"));
                    JSONArray contentObject1 = JSONArray.fromObject(content1.getString("questionItemObjects"));
                    List<Object> answList = new ArrayList<>();
                    if (contentObject1.size() == 0) {
                        map2.put("questionItemObjects", null);
                    } else {
                        for (int j = 0; j < contentObject1.size(); j++) {
                            JSONObject xuanxiang = contentObject1.getJSONObject(j);
                            Map<String, String> map4 = new HashMap();
                            map4.put("prefix", xuanxiang.getString("prefix"));
                            map4.put("content", xuanxiang.getString("content"));
                            map4.put("score", xuanxiang.getString("score"));
                            answList.add(map4);
                        }
                        map2.put("questionItemObjects", answList);
                    }

                }
                redisUtils.saveValue("adminQuestion"+id,map2);
                return Result.succ(200, "查询成功", map2);
            } else {
                return Result.fail("该题目不存在");
            }
        }
    }

    //题目编辑
    @PutMapping("/question")
    @ApiOperation("编辑题目信息")
    public Result editQuestion(@RequestBody QuestionView questionView) {
        UpdateWrapper updateQuery = new UpdateWrapper<>();
        updateQuery.eq("id",questionView.getId());
        updateQuery.set("question_type",questionView.getQuestionType());
        updateQuery.set("subject_id",questionView.getSubjectId());
        updateQuery.set("score",questionView.getScore());
        updateQuery.set("grade_level",questionView.getGradeLevel());
        updateQuery.set("difficult",questionView.getDifficult());
        updateQuery.set("correct",questionView.getCorrect());

        Question question=questionMapper.selectById(questionView.getId());
        System.out.println("找到问题ID"+questionView.getId());
        System.out.println("根据问题ID获取到问题了"+question);
        TextContent textContent=textContentMapper.selectById(question.getInfoTextContentId());
        System.out.println("根据问题-content-ID获取到content了"+textContent);
        JSONArray jsonArray=JSONArray.fromObject(textContent.getContent());
        UpdateWrapper updateQuery1=new UpdateWrapper<>();
        updateQuery1.eq("id",textContent.getId());
        updateQuery1.set("content",jsonArray.toString());
        updateQuery1.set("create_time",new Date());
        int result1  = textContentMapper.update(null,updateQuery1);
        if(result1>0){
            System.out.println("更新题目content内容成功");
            int result=questionMapper.update(null,updateQuery);
            if(result>0){
                //管理员登录的日志
                super.adminLog("admin修改了问题"+questionView.getId());
                redisUtils.delAll();
                return Result.succ(200,"编辑成功",null);
            }else {
                return Result.fail("编辑失败");
            }
        }else {
            return Result.fail("编辑失败");
        }
    }

    //题目创编
    @PostMapping("/question")
    @ApiOperation("题目创编")
    public Result addQuestion(@RequestBody QuestionView questionView){
        TextContent textContent=new TextContent();
        JSONObject jsonObject=JSONObject.fromObject(questionView.getContent());
        textContent.setContent(jsonObject.toString());
        textContent.setCreateTime(new Date());
        int result=textContentMapper.insert(textContent);
        if(result>0){
            Question question=new Question();
            question.setQuestionType(questionView.getQuestionType());
            question.setSubjectId(questionView.getSubjectId());
            question.setScore(questionView.getScore());
            question.setGradeLevel(questionView.getGradeLevel());
            question.setDifficult(questionView.getDifficult());
            question.setCorrect(questionView.getCorrect());
            question.setStatus(1);
            question.setCreateUser(2);
            question.setCreateTime(new Date());
            question.setInfoTextContentId(textContent.getId());
            int result1 =questionMapper.insert(question);
            if (result1>0){
                super.adminLog("管理员添加了题目"+question.getId());
                redisUtils.delAll();
                return Result.succ("添加成功");
            }else{
                return Result.fail("添加失败");
            }
        }else{
            return Result.fail("添加失败");
        }

    }

    //题目删除
    @DeleteMapping("/question/{id}")
    @ApiOperation("删除题目")
    public Result deleteQuestion(@PathVariable("id") Integer id) {

        int result = questionMapper.deleteById(id);
        if(result>0){
            super.adminLog("admin删除了题目"+id);
            redisUtils.delAll();
            return Result.succ("删除成功",null);
        }else {
            return Result.fail("删除失败");
        }
    }

}

